package com.duang.netty.agreement.utils;

import com.duang.netty.agreement.struct.NettyMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.io.IOException;
import java.util.List;
import java.util.Map;
//netty 消息编码类
public class NettyMessageEncoder extends MessageToMessageEncoder<NettyMessage> {

    MarshallingEncoder marshallingEncoder;

    public NettyMessageEncoder() throws IOException {
        this.marshallingEncoder = new MarshallingEncoder();
    }

    public void encode(ChannelHandlerContext ctx, NettyMessage msg, List<Object> out) throws Exception {
        if (msg ==null || msg.getHeader()==null){
            throw new Exception("The encode message is null");
        }
        ByteBuf sendBuf = Unpooled.buffer();
        sendBuf.writeInt(msg.getHeader().getCrcCode());//四个字节
        sendBuf.writeInt(msg.getHeader().getLength());//四个字节   消息长度
        sendBuf.writeLong(msg.getHeader().getSessionID());//八个字节  绘画id
        sendBuf.writeByte(msg.getHeader().getType());//1
        sendBuf.writeByte(msg.getHeader().getPriority());//1
        sendBuf.writeInt(msg.getHeader().getAttachment().size());//4  附件 个数
        String key =null;
        byte[] keyArray = null;
        Object value = null;
        for(Map.Entry<String,Object> param:msg.getHeader().getAttachment().entrySet()){
            key = param.getKey();
            keyArray = key.getBytes("UTF-8");
            sendBuf.writeInt(keyArray.length);//一个附件的key的长度
            sendBuf.writeBytes(keyArray);//附件key 字节流
            value = param.getValue();
            marshallingEncoder.encode(value,sendBuf);
        }
        key = null;
        keyArray = null;
        value = null ;
        if(msg.getBody()!=null){
            marshallingEncoder.encode(msg.getBody(),sendBuf);
        }else{
            sendBuf.writeInt(0);//body长度为0
        }
        sendBuf.setInt(4,sendBuf.readableBytes());
        out.add(sendBuf);
    }
}
